﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.SharePoint.Common.Configuration;
using Microsoft.Practices.SharePoint.Common.Logging;
using Microsoft.Practices.SharePoint.Common.ServiceLocation;

namespace SharePoint.Contrib
{
    /// <summary>
    /// Utility class for working with the Patterns and Practices SharePoint Guidance library (SPG)
    /// </summary>
    internal static class SPG
    {
        /// <summary>
        /// Gets the default instance of the IConfigManager.
        /// </summary>
        public static IConfigManager ConfigManager
        {
            get
            {
                var ConfigManager = SharePointServiceLocator
                            .GetCurrent()
                            .GetInstance<IConfigManager>();
                return ConfigManager;
            }
        }

        public static ILogger Logger
        {
            get
            {
                return SharePointServiceLocator
                                    .GetCurrent()
                                    .GetInstance<ILogger>();
            }
        }

        public static string AreaAndCategory(string area, string category)
        {
            return string.Concat(area, Microsoft.Practices.SharePoint.Common.Constants.CategoryPathSeparator, category);
        }

        public static Dictionary<string, string> RemoveNamespaceFromKeys(Dictionary<string, string> settings)
        {
            return (from setting in settings
                    select new
                    {
                        Key = RemoveSPGNamespaceFromKey(setting.Key),
                        Value = setting.Value
                    })
                        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
        }

        private static string RemoveSPGNamespaceFromKey(string key)
        {
            return key
                    .Replace(PNPNamespacePrefix, string.Empty)
                    .Replace(PNPSiteCollectionNamespaceSuffix, string.Empty);
        }

        public static string PNPNamespacePrefix
        {
            get
            { 
                return string.Concat(Microsoft.Practices.SharePoint.Common.Configuration.ConfigManager.PnPKeyNamespace, ".");
            }
        }

        public static string PNPSiteCollectionNamespaceSuffix
        {
            get
            {
                return SPSitePropertyBag.KeySuffix;
            }
        }

    }
}
